package com.group18.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.group18.entity.FamilyUser;
import com.group18.entity.MemberUser;
import com.group18.service.FamilyUserService;
import com.group18.service.MemberUserService;

/**
 * Servlet implementation class DoLogin
 */
@WebServlet("/DoLogin")
public class DoLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		String msg = "";
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		MemberUser mu = new MemberUser();
		mu.setUsername(username);
		mu.setPassword(password);
		
		MemberUserService mus = new MemberUserService();
		if(mus.isExist(mu)) {//查询用户是否存在
			if(mus.login(mu)) {
				
				String name = mus.selectNameByUsername(mu);
				int member_id = mus.selectIdByUsername(mu);
				
				FamilyUser fu = new FamilyUser();
				fu.setName(name);
				FamilyUserService fus = new FamilyUserService();
				int family_id = fus.selectIDByName(fu);
				
				HttpSession session = request.getSession();
				session.setAttribute("name", name);
				session.setAttribute("member_id", member_id);
				session.setAttribute("username", username);
				session.setAttribute("family_id", family_id);
				session.setAttribute("password", password);
				
				request.getRequestDispatcher("/ToIndex").forward(request, response);
			}else {
				msg = "密码错误";
				request.setAttribute("msg", msg);
				request.getRequestDispatcher("/ToLogin").forward(request, response);
			}
		}else {
			msg = "该用户名不存在";
			request.setAttribute("msg", msg);
			request.getRequestDispatcher("/ToLogin").forward(request, response);
		}
	}

}
